package com.xs.ahoi.hcxs.utils;

import android.util.Log;

import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;

/**
 * author: ahoi
 * date: 2018/6/24 20:05
 * description:
 */
public class LogUtil {

    private static final boolean debugger = true;
    private static final String tag = "iiii";
    private static RandomAccessFile r;

    static {
        try {
            FileUtil.checkAndCreateDir(Constants.ERROR_LOG_PATH);
            r = new RandomAccessFile(Constants.ERROR_LOG_PATH, "rw");
        } catch (Exception e) {
            e("an error occur while write log to logfile!", e);
        }
    }

    public static void e(String msg) {
        e(msg, null);
    }

    public static void e(String msg, Throwable t) {
        if (debugger) {
            Log.e(tag, "=======================================" + msg, t);
        }
        if (t != null) {
            msg = getErrorInfo(msg, t);
        }
        flush(msg);
    }

    private static void flush(String msg) {
        try {
            FileUtil.checkAndCreateDir(Constants.ERROR_LOG_PATH);
            msg = "\n\n" + DateUtil.date2String(new Date(), DateUtil.FORMAT_YMD_HMS) + ": " + msg;
            r.seek(r.length());
            r.write(msg.getBytes(Constants.DEFAULT_CHARSET));
        } catch (Exception ignored) {
        }
    }


    public static String getErrorInfo(String msg, Throwable t) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        t.printStackTrace(printWriter);
        Throwable cause = t.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        return msg + ":\n" + writer.toString();
    }

}
